package com.weijian.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weijian.common.ApiResponse;
import com.weijian.dal.dto.study.ProgressUpdateRequest;
import com.weijian.dal.dto.study.StudyRecordDTO;
import com.weijian.dal.dto.study.StudyStatisticsDTO;
import com.weijian.service.StudyRecordService;
import com.weijian.util.SessionUserUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 学习记录控制器
 *
 * @author weijian
 */
@Slf4j
@RestController
@RequestMapping("/api/study")
@RequiredArgsConstructor
@Validated
@Tag(name = "学习记录管理", description = "学习记录、进度管理、学习统计等相关接口")
public class StudyRecordController {

    private final StudyRecordService studyRecordService;

    /**
     * 开始学习课程
     */
    @Operation(summary = "开始学习课程", description = "用户开始新的课程学习，创建学习记录")
    @PostMapping("/start/{courseId}")
    public ApiResponse<StudyRecordDTO> startStudy(
            @Parameter(description = "课程ID", required = true, example = "1")
            @PathVariable Long courseId,
            @Parameter(description = "用户ID", required = true, example = "1")
            @RequestParam Long userId) {

        log.info("开始学习课程请求：userId={}, courseId={}", userId, courseId);
        try {
            StudyRecordDTO result = studyRecordService.startStudy(userId, courseId);
            return ApiResponse.success("开始学习成功", result);
        } catch (Exception e) {
            log.error("开始学习失败", e);
            return ApiResponse.error(400, "开始学习失败：" + e.getMessage());
        }
    }

    /**
     * 更新学习进度
     */
    @Operation(summary = "更新学习进度", description = "更新用户的学习进度，包括已完成章节数和学习时长")
    @PutMapping("/progress/{courseId}")
    public ApiResponse<StudyRecordDTO> updateProgress(
            @Parameter(description = "课程ID", required = true, example = "1")
            @PathVariable Long courseId,
            @Parameter(description = "用户ID", required = true, example = "1")
            @RequestParam Long userId,
            @Valid @RequestBody ProgressUpdateRequest request) {

        log.info("更新学习进度请求：userId={}, courseId={}, request={}",
                userId, courseId, request);

        // 设置课程ID
        request.setCourseId(courseId);

        try {
            StudyRecordDTO result = studyRecordService.updateProgress(userId, request);
            return ApiResponse.success("更新进度成功", result);
        } catch (Exception e) {
            log.error("更新进度失败", e);
            return ApiResponse.error(401, "更新进度失败：" + e.getMessage());
        }
    }

    /**
     * 完成课程学习
     */
    @Operation(summary = "完成课程学习", description = "标记课程为已完成状态，更新完成时间和进度")
    @PutMapping("/complete/{courseId}")
    public ApiResponse<StudyRecordDTO> completeCourse(
            @Parameter(description = "课程ID", required = true, example = "1")
            @PathVariable Long courseId,
            @Parameter(description = "用户ID", required = true, example = "1")
            @RequestParam Long userId) {

        log.info("完成课程学习请求：userId={}, courseId={}", userId, courseId);
        try {
            StudyRecordDTO result = studyRecordService.completeCourse(userId, courseId);
            return ApiResponse.success("课程完成成功", result);
        } catch (Exception e) {
            log.error("完成课程失败", e);
            return ApiResponse.error(401, "完成课程失败：" + e.getMessage());
        }
    }

    /**
     * 获取学习记录
     */
    @Operation(summary = "获取学习记录", description = "获取用户指定课程的学习记录详情")
    @GetMapping("/record/{courseId}")
    public ApiResponse<StudyRecordDTO> getStudyRecord(
            @Parameter(description = "课程ID", required = true, example = "1")
            @PathVariable Long courseId,
            @Parameter(description = "用户ID", required = true, example = "1")
            @RequestParam Long userId) {

        log.info("获取学习记录请求：userId={}, courseId={}", userId, courseId);
        try {
            StudyRecordDTO result = studyRecordService.getStudyRecord(userId, courseId);
            if (result == null) {
                return ApiResponse.error(401, "学习记录不存在");
            }
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取学习记录失败", e);
            return ApiResponse.error(401, "获取学习记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户的学习记录列表
     */
    @Operation(summary = "获取用户的学习记录列表", description = "分页获取用户的所有学习记录")
    @GetMapping("/my-records")
    public ApiResponse<IPage<StudyRecordDTO>> getUserStudyRecords(
            @Parameter(description = "用户ID", required = true, example = "1")
            @RequestParam Long userId,
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页条数", example = "10")
            @RequestParam(defaultValue = "10") Integer size) {

        log.info("获取用户学习记录列表请求：userId={}, page={}, size={}", userId, page, size);
        try {
            Page<StudyRecordDTO> pageParam = new Page<>(page, size);
            IPage<StudyRecordDTO> result = studyRecordService.getUserStudyRecords(pageParam, userId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取学习记录列表失败", e);
            return ApiResponse.error(401, "获取学习记录列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取学习中的课程
     */
    @Operation(summary = "获取学习中的课程", description = "获取用户当前正在学习的课程列表")
    @GetMapping("/in-progress")
    public ApiResponse<List<StudyRecordDTO>> getInProgressCourses(
            @Parameter(description = "用户ID", required = true, example = "1")
            @RequestParam Long userId) {

        log.info("获取学习中课程请求：userId={}", userId);
        try {
            List<StudyRecordDTO> result = studyRecordService.getInProgressCourses(userId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取学习中课程失败", e);
            return ApiResponse.error(401, "获取学习中课程失败：" + e.getMessage());
        }
    }

    /**
     * 获取已完成的课程
     */
    @Operation(summary = "获取已完成的课程", description = "获取用户已完成的课程列表")
    @GetMapping("/completed")
    public ApiResponse<List<StudyRecordDTO>> getCompletedCourses(
            @Parameter(description = "用户ID", required = true, example = "1")
            @RequestParam Long userId) {

        log.info("获取已完成课程请求：userId={}", userId);
        try {
            List<StudyRecordDTO> result = studyRecordService.getCompletedCourses(userId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取已完成课程失败", e);
            return ApiResponse.error(401, "获取已完成课程失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户学习统计
     */
    @GetMapping("/summary")
    @Operation(summary = "获取用户学习统计", description = "获取当前登录用户的学习统计数据")
    public ApiResponse<StudyStatisticsDTO> getUserStudySummary() {
        Long userId = SessionUserUtil.getCurrentUserId();
        StudyStatisticsDTO summary = studyRecordService.getUserStudySummary(userId);
        return ApiResponse.success(summary);
    }

    /**
     * 获取学习排行榜
     */
    @Operation(summary = "获取学习排行榜", description = "获取学习排行榜，支持日榜、周榜、总榜")
    @GetMapping("/leaderboard")
    public ApiResponse<List<StudyRecordDTO>> getStudyLeaderboard(
            @Parameter(description = "排行榜类型：daily(日榜), weekly(周榜), overall(总榜)",
                    example = "overall")
            @RequestParam(defaultValue = "overall") String type) {

        log.info("获取学习排行榜请求：type={}", type);
        try {
            List<StudyRecordDTO> result = studyRecordService.getStudyLeaderboard(type);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取排行榜失败", e);
            return ApiResponse.error(401, "获取排行榜失败：" + e.getMessage());
        }
    }
}